import re
import os

from django.utils         import timezone, safestring

import config.settings as settings
from print_request.models import Request
import prenstar


def handle_imported_file(f, name, short, descr):
  filename = str(f)
  extension = re.sub(r'.*\.(.*)$', '\\1', filename)

  r = Request(
      name              = name,
      extension         = extension,
      pub_date          = timezone.now(),
      short_description = short,
      description       = descr)
  r.save()

  output_file  = os.path.join(settings.MEDIA_ROOT, str(r.id) + '.' + extension)
  preview_file = os.path.join(settings.MEDIA_ROOT, str(r.id) + '-preview.stl')
  with open(output_file,'wb+') as destination:
    for chunk in f.chunks():
      destination.write(chunk)

  prenstar.translate_mesh_for_preview(output_file, preview_file)

  return r

def get_extension_description(ext):
  filename = 'print_request/static/print_request/ext/' + ext
  if os.path.exists(filename):
    with open(filename) as source:
      return safestring.SafeText(source.read())
  else:
    return "Unhandled extension."
